package edu.qichen.onlineBlog.framework;

import edu.qichen.onlineBlog.log.pojo.LoginLog;
import edu.qichen.onlineBlog.log.pojo.Syslog;
import edu.qichen.onlineBlog.log.service.LoginLogService;
import edu.qichen.onlineBlog.log.service.SyslogService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 功能:
 * 作者:程序员欧阳子韩
 * 日期:2024/5/1 14:15
 */
@Slf4j
@Component
public class LogTask {
    @Resource
    LogQueue logQueue;

    @Resource
    SyslogService syslogService;

    @Resource
    LoginQueue loginQueue;

    @Resource
    LoginLogService loginLogService;

    private volatile List<Syslog> operaLogs = Collections.synchronizedList(new ArrayList<>());

    private volatile List<LoginLog> loginLogs = Collections.synchronizedList(new ArrayList<>());

    @Scheduled(fixedRate = 5000)// 每隔一分钟执行一次
    public void logFixDelay() {
        log.info("存入操作日志");
        // 获取日志信息
        while (true) {
            Syslog operaLog = logQueue.poll();
            if (null == operaLog) {
                break;
            }
            operaLogs.add(operaLog);
        }
        if (!operaLogs.isEmpty()) {
            try {
                log.info("######################批量添加操作日志" + operaLogs.size());
                syslogService.insetAll(operaLogs);
            } catch (Exception e) {
                log.error("批量添加操作日志异常:", e);
                operaLogs.clear();
            }
            operaLogs.clear();
        }
    }

    @Scheduled(fixedRate = 5000)// 每隔一分钟执行一次
    public void loginFixDelay() {
        log.info("存入登录日志");
        // 获取日志信息
        while (true) {
            LoginLog logs = loginQueue.poll();
            if (null == logs) {
                break;
            }
            loginLogs.add(logs);
        }
        if (!loginLogs.isEmpty()) {
            try {
                log.info("######################批量添加登录日志" + loginLogs.size());
                loginLogService.insertAll(loginLogs);
            } catch (Exception e) {
                log.error("批量添加登录日志异常:", e);
                loginLogs.clear();
            }
            loginLogs.clear();
        }
    }
}
